<?php
class HashGenerator {
	
	// Cleartext to salted hash
	// $clearPassword - the password to hash
	// returns - the hash of the password (128 hex characters)
	public static function hashClearPassword($clearPassword) {
		// Generate a 256 bit random salt using CSPRNG function
		$greatSalt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
	
		// Take our new salt and prepend the password and hash the lot
		$hash = hash("sha256", $greatSalt . $clearPassword);
	
		// Combine the salt with the hash so you get 128 characters
		$returnValue = $greatSalt . $hash;
		return $returnValue;
	}
	
	// Check hash
	// return true if hash is the correct for that password
	// $correctHash - the hash stored in our db or created by hashClearPassword()
	// $clearPassword - the password to verify
	// returns - true if the password is valid | false if it isn't
	public static function validatePassword($clearPassword, $correctHash) {
	
		// Extract the salt from the string
		$ourSalt = substr($correctHash, 0, 64);
	
		// Extract the hash from the string
		$validHash = substr($correctHash, 64, 64);
	
		// Generate a hash for comparison
		$compareHash = hash("sha256", $ourSalt . $clearPassword);
		// Test the validHash against the one from the supplied password
		return $compareHash === $validHash;
	}
}